using Infrastructure.Attribute;
using SqlSugar;
using ZR.Model;
using ZR.Model.System;
using ZR.Model.System.Dto;
using ZR.ServiceCore.Services.IService;

namespace ZR.ServiceCore.Services
{
    /// <summary>
    /// 表元数据服务
    /// </summary>
    [AppService(ServiceType = typeof(ITableMetadataService), ServiceLifetime = LifeTime.Transient)]
    public class TableMetadataService : BaseService<TableMetadata>, ITableMetadataService
    {
        /// <inheritdoc/>
        public PagedInfo<TableMetadataDto> GetTableMetadataList(TableMetadataQueryDto query, PagerInfo pager)
        {
            var expression = Expressionable.Create<TableMetadata>();

            if (!string.IsNullOrEmpty(query.City))
            {
                expression.And(x => x.City == query.City);
            }

            if (!string.IsNullOrEmpty(query.Type))
            {
                expression.And(x => x.Type == query.Type);
            }

            if (!string.IsNullOrEmpty(query.SchemaName))
            {
                expression.And(x => x.SchemaName == query.SchemaName);
            }

            // 根据syncTime字段进行日期范围过滤
            if (query.BeginTime.HasValue)
            {
                expression.And(x => x.SyncTime >= query.BeginTime.Value);
            }

            if (query.EndTime.HasValue)
            {
                // 结束日期包含当天的23:59:59
                var endTime = query.EndTime.Value.Date.AddDays(1).AddSeconds(-1);
                expression.And(x => x.SyncTime <= endTime);
            }

            var total = 0;
            var list = Context.Queryable<TableMetadata>()
                .Where(expression.ToExpression())
                .OrderBy(x => x.SyncTime, OrderByType.Desc)
                .Select(x => new TableMetadataDto
                {
                    Id = x.Id,
                    TableName = x.TableName,
                    DatePrefix = x.DatePrefix,
                    DayPrefix = x.DayPrefix,
                    City = x.City,
                    Type = x.Type,
                    SchemaName = x.SchemaName,
                    SyncTime = x.SyncTime
                })
                .ToPageList(pager.PageNum, pager.PageSize, ref total);

            return new PagedInfo<TableMetadataDto>
            {
                TotalNum = total,
                Result = list,
                PageIndex = pager.PageNum,
                PageSize = pager.PageSize
            };
        }
    }
}

